package com.syqc.videos.players

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.TextView
import androidx.appcompat.widget.AppCompatSeekBar
import androidx.core.view.isVisible
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView
import com.shuyu.gsyvideoplayer.video.base.GSYVideoViewBridge
import com.syqc.monitor.R
import com.syqc.utils.TimeUtil
import com.syqc.videos.videomanager.TapeManager
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import java.util.concurrent.TimeUnit

class StopPlayer : StandardGSYVideoPlayer {

    constructor(context: Context, fullFlag: Boolean) : super(context, fullFlag)
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)


    //数据类型
    private var mType: Int = 0

    //是否需要静音
    private var isNeedMute = true

    private var mProgress: Long = 0
    private var maxProgress: Long = 0

    //最大时间
    private var maxStrTime = TimeUtil.zeroHms


    private lateinit var ivSwitchVoice: ImageView
    private lateinit var tvSwitchScale: TextView
    private lateinit var tvTmnStart: TextView
    private lateinit var tvTmnEnd: TextView
    private lateinit var videoProgress: AppCompatSeekBar
    private lateinit var loadingProgress: ProgressBar

    private lateinit var startPlay: ImageView

    private var listener: com.syqc.videos.interfaces.ITmnListener? = null


    override fun getLayoutId(): Int {
        return R.layout.stop_video_tmn
    }

    override fun init(context: Context?) {
        super.init(context)
        initParams()
        initView()
        setListener()
    }

    private fun initParams() {
        isRotateViewAuto = true
        isLockLand = true
        isReleaseWhenLossAudio = false
        isShowFullAnimation = true
        setIsTouchWiget(false)
        setIsTouchWigetFull(false)

        isNeedMute = true
        TapeManager.instance.isNeedMute = isNeedMute
    }


    private fun initView() {
        ivSwitchVoice = findViewById(R.id.ivSwitchVoice)
        tvSwitchScale = findViewById(R.id.tvSwitchScale)
        loadingProgress = findViewById(R.id.loadingProgress)
        startPlay = findViewById(R.id.startPlay)
        videoProgress = findViewById(R.id.videoProgress)
        tvTmnStart = findViewById(R.id.tvTmnStart)
        tvTmnEnd = findViewById(R.id.tvTmnEnd)
        ivSwitchVoice.isSelected = isNeedMute
    }

    private fun setListener() {
        //声音
        ivSwitchVoice.setOnClickListener {
            isNeedMute = !isNeedMute
            ivSwitchVoice.isSelected = isNeedMute
            TapeManager.instance.isNeedMute = isNeedMute
        }
        //比例
        tvSwitchScale.setOnClickListener {
            if (!mHadPlay) {
                return@setOnClickListener
            }
            when (mType) {
                0 -> mType = 1
                1 -> mType = 2
                2 -> mType = 3
                3 -> mType = 4
                4 -> mType = 0
            }
            resolveTypeUI()
            
        }
        startPlay.setOnClickListener {
            listener?.onPlaying(isInPlayingState)
        }

        videoProgress.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (!mHadPlay) return
                mProgress = progress.toLong()
                tvTmnStart.text = "${TimeUtil.instance.formatLongTime(mProgress)}"
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                stopTime()
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                listener?.onSeekProgress(mProgress)
            }
        })
    }

    fun setTmnListener(listener: com.syqc.videos.interfaces.ITmnListener) {
        this.listener = listener
    }



    ////////////////////////////////////////////////////////////////////////////////////////////


    /**
     * 显示比例
     * 注意，GSYVideoType.setShowType是全局静态生效，除非重启APP。
     */
    private fun resolveTypeUI() {
        if (!mHadPlay) {
            return
        }
        when (mType) {
            1 -> {
                tvSwitchScale.text = "16:9"
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_16_9)
            }

            2 -> {
                tvSwitchScale.text = "4:3"
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_4_3)
            }

            3 -> {
                tvSwitchScale.setText(R.string.desc_video_full_screen)
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL)
            }

            0 -> {
                tvSwitchScale.setText(R.string.desc_video_default_ratio)
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_DEFAULT)
            }
        }
        changeTextureViewShowType()
        if (mTextureView != null) mTextureView.requestLayout()
    }


    override fun getGSYVideoManager(): GSYVideoViewBridge {
        TapeManager.instance.initContext(context.applicationContext)
        return TapeManager.instance
    }

    override fun setStateAndUi(state: Int) {
        super.setStateAndUi(state)
        when (state) {
            GSYVideoView.CURRENT_STATE_PLAYING -> {
                startPlay.isVisible = false
            }

            GSYVideoView.CURRENT_STATE_PAUSE,
            GSYVideoView.CURRENT_STATE_AUTO_COMPLETE,
            GSYVideoView.CURRENT_STATE_ERROR -> stopTime()
        }
    }

    override fun touchSurfaceMoveFullLogic(absDeltaX: Float, absDeltaY: Float) {
        super.touchSurfaceMoveFullLogic(absDeltaX, absDeltaY)
        //不给触摸快进，如果需要，屏蔽下方代码即可
        mChangePosition = false

        //不给触摸音量，如果需要，屏蔽下方代码即可
        mChangeVolume = false

        //不给触摸亮度，如果需要，屏蔽下方代码即可
        mBrightness = false
    }

    override fun touchDoubleUp(e: MotionEvent?) {
//        super.touchDoubleUp(e)
    }

    /////////////////////////////////////////////////////////////////////////////////////////////
    fun showStartPlay(isShow: Boolean) {
        startPlay.isVisible = isShow
    }

    /**
     * 是否展示进度
     *
     * @param isShow
     */
    fun showProgress(isShow: Boolean) {
        loadingProgress.isVisible = isShow
        if (isShow) startPlay.isVisible = false
    }


    /** 设置seekbar状态 */
    fun setSeekBarState(time: Long) {
        maxProgress = time
        maxStrTime = TimeUtil.instance.formatLongTime(time)
        videoProgress.max = time.toInt()
        videoProgress.progress = 0
        mProgress = 0
        tvTmnStart.text = "${TimeUtil.zeroHms} "
        tvTmnEnd.text=maxStrTime
    }

    /** 设置seekbar状态 */
    fun setSeekBarProgress(progress: Long, maxTime: Long) {
        maxProgress = maxTime
        mProgress = progress
        maxStrTime = TimeUtil.instance.formatLongTime(maxTime)
        videoProgress.max = maxTime.toInt()
        videoProgress.progress = progress.toInt()
        tvTmnStart.text = "${TimeUtil.instance.formatLongTime(mProgress)}"
        tvTmnEnd.text=maxStrTime
    }

    private var disposable: Disposable? = null

    fun startTime() {
        stopTime()
        disposable = Observable.interval(0, 1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (mProgress >= maxProgress) {
                    listener?.onProgress(mProgress)
                    stopTime()
                }
                videoProgress.progress = mProgress.toInt()
                tvTmnStart.text = "${TimeUtil.instance.formatLongTime(mProgress)}"
                mProgress += 1000
            }
    }

    fun stopTime() {
        if (disposable != null && disposable?.isDisposed == false) {
            disposable?.dispose()
            disposable = null
        }
    }


}